package com.navercorp.pinpoint.web.dao.es;

import com.navercorp.pinpoint.common.hbase.HBaseTables;
import com.navercorp.pinpoint.common.server.bo.AgentInfoBo;
import com.navercorp.pinpoint.web.dao.es.entity.AgentInfoEntity;
import com.navercorp.pinpoint.web.dao.es.entity.ApplicationEntity;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.Index;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.IOException;

@Repository
public class EsApplicationIndexDao {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JestClient jestClient;

    /**
     * 插入应用注册信息
     * @param agentInfo
     */
    public void insert(AgentInfoEntity agentInfo) {
        if (agentInfo == null) {
            throw new NullPointerException("agentInfo must not be null");
        }
        ApplicationEntity application = new ApplicationEntity();
        BeanUtils.copyProperties(agentInfo,application);
        application.setServiceTypeCode(agentInfo.getServiceTypeCode());   //BeanUtils未copy该属性 TODO problem
        Index.Builder builder = new Index.Builder(application);
        builder.id(application.getApplicationName());
        builder.refresh(true);
        Index default_space = builder.index("default_space").type(HBaseTables.APPLICATION_INDEX_STR).build();
        JestResult result;
        try {
            result = jestClient.execute(default_space);
            if (result != null && result.isSucceeded()) {
                logger.info("ESJestClient insert ApplicationIndex success");
            }
        } catch (IOException e) {
            logger.error("ESJestClient insertDoc ApplicationIndex exception", e);
        }
    }

}
